package com.study.utils;

import java.security.MessageDigest;

/**
 * MD5加密算法工具类
 */
public class MD5Util {
    /**
     * MD5加码 生成32位md5码
     * @param inStr 加密字符串
     * @return 32位MD5加码
     */
    public static String MD5Encryption(String inStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     */
    public static String convertMD5(String inStr) {
        char[] charArray = inStr.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            charArray[i] = (char) (charArray[i] ^ 't');
        }
//        String s = new String(charArray);
//        return Arrays.toString(charArray);
        return new String(charArray);
    }

//    public static void main(String[] args) {
//        String s = new String("123456");
//        System.out.println("原始：" + s);
//        System.out.println("MD5后：" + MD5Encryption(s));
//        System.out.println("加密的：" + convertMD5(s));
//        System.out.println("解密的：" + convertMD5(convertMD5(s)));
//    }
}